package com.jihui.jihuipicturebackend.manager;

import cn.hutool.core.io.FileUtil;
import com.jihui.jihuipicturebackend.config.CosClientConfig;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.model.COSObject;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.model.ciModel.persistence.PicOperations;
import org.springframework.context.annotation.Configuration;


import javax.annotation.Resource;
import java.io.File;
import java.util.ArrayList;
import java.util.List;

@Configuration
public class CosManager {

    @Resource
    CosClientConfig cosClientConfig;

    @Resource
    COSClient cosClient;

    /**
     * 上传对象
     *
     * @param key  唯一键
     * @param file 文件
     */
    public PutObjectResult putObject(String key, File file) {
        PutObjectRequest putObjectRequest = new PutObjectRequest(cosClientConfig.getBucket(), key,
                file);
        return cosClient.putObject(putObjectRequest);
    }

    /**
     * 下载对象
     * @param key
     * @return
     */
    public COSObject getObject(String key) {
        return cosClient.getObject(cosClientConfig.getBucket(), key);
    }

    /**
     * 上传对象(附带图片信息)
     *
     * @param key  唯一键
     * @param file 文件
     */
    public PutObjectResult putPictureObject(String key, File file) {
        PutObjectRequest putObjectRequest = new PutObjectRequest(cosClientConfig.getBucket(), key, file);
        // 图片处理参数
        PicOperations picOperation = new PicOperations();
        // 返回原始图片
        picOperation.setIsPicInfo(1);
        // 设置上传图片时需要进行的相关操作
        List<PicOperations.Rule> rules = new ArrayList<>();
        PicOperations.Rule compressRule = new PicOperations.Rule();
        String fileidKey = FileUtil.mainName(key) + ".webp";
        // 以webp格式进行处理
        compressRule.setRule("imageView2/format/webp");
        compressRule.setFileId(fileidKey);
        compressRule.setBucket(cosClientConfig.getBucket());
        rules.add(compressRule);

        PicOperations.Rule thumbnailRule = new PicOperations.Rule();
        // 生成缩略图，大小为128x128
        if(file.length() > 2 * 1024){ // 仅对 > 20 KB 的图片生成缩略图
            String thumbnailKey = FileUtil.mainName(key) + "_thumbnail" + FileUtil.getSuffix(key);
            thumbnailRule.setFileId(thumbnailKey);
            thumbnailRule.setBucket(cosClientConfig.getBucket());
            thumbnailRule.setRule(String.format("imageMogr2/thumbnail/%sx%s>", 256, 256));
            rules.add(thumbnailRule);
        }
        // 构造处理参数
        picOperation.setRules(rules);
        putObjectRequest.setPicOperations(picOperation);
        return cosClient.putObject(putObjectRequest);
    }

    /**
     * 删除对象
     * @param key
     */
    public void deleteObject(String key){
        cosClient.deleteObject(cosClientConfig.getBucket(), key);
    }

}
